package com.learn.concurrent.itcast.thread.demo;

/**
 * 线程间通信常用方式如下：
 * 	休眠唤醒方式：Object的wait、notify、notifyAll
 *                 Condition的await、signal、signalAll
 * 	CountDownLatch：用于某个线程A等待若干个其他线程执行完之后，它才执行
 * 	CyclicBarrier：一组线程等待至某个状态之后再全部同时执行
 * 	Semaphore：用于控制对某组资源的访问权限
 */
public class WaitNotifyRunnable {

    private int i=0;//要打印的数
    private Object obj=new Object();

    /**
     * 奇数打印方法，由奇数线程调用
     */
    public void odd() {
        while(i<10){
            synchronized (obj){
                if(i%2==1){
                    System.out.println("奇数："+i);
                    i++;
                    obj.notify();
                }else{
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 偶数打印方法，由偶数线程调用
     */
    public void even(){
        while(i<10){
            synchronized (obj){
                if(i%2==0){
                    System.out.println("偶数："+i);
                    i++;
                    obj.notify();
                }else{
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    public static void main(String[] args) {

        WaitNotifyRunnable demo=new WaitNotifyRunnable();
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                demo.odd();
            }
        },"奇数线程");

        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                demo.even();
            }
        },"偶数线程");

        thread1.start();
        thread2.start();
    }
}
